<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="发票编号" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入发票编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="客户" prop="customerId">
        <!-- <el-input
          v-model="queryParams.customerName"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        /> -->
        <el-select
          v-model="queryParams.customerId"
          class="!w-240px"
          filterable
          placeholder="请选择客户"
        >
          <el-option
            v-for="item in customerList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="合同名称" prop="contractName">
        <el-input
          v-model="queryParams.contractName"
          placeholder="请输入合同名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="开票类型" prop="receiptType">
        <el-select
          v-model="queryParams.receiptType"
          placeholder="请选择开票类型"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.CRM_RECEIPT_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="开票状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择开票状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.CRM_RECEIPT_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['crm:receipt:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['crm:receipt:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
          type="danger"
          plain
          :disabled="isEmpty(checkedIds)"
          @click="handleDeleteBatch"
          v-hasPermi="['crm:receipt:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <ContentWrap>
    <el-tabs v-model="activeName" @tab-click="handleTabClick">
      <el-tab-pane label="我负责的" name="1" />
      <el-tab-pane label="我参与的" name="2" />
      <el-tab-pane label="下属负责的" name="3" />
    </el-tabs>
    <el-table v-loading="loading" :data="list" :show-overflow-tooltip="true" :stripe="true">
      <el-table-column type="selection" width="55" />
      <el-table-column label="发票编号" align="center" prop="code" />
      <el-table-column label="开票内容" align="center" prop="content" />
      <el-table-column label="客户名称" align="center" prop="customerName" />
      <el-table-column label="合同名称" align="center" prop="contractName" />
      <el-table-column label="开票金额" align="center" prop="receiptAmount" />
      <el-table-column
        label="开票日期"
        align="center"
        prop="receiptDate"
        :formatter="dateFormatter2"
      />
      <el-table-column label="开票类型" align="center" prop="receiptType">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.CRM_RECEIPT_TYPE" :value="scope.row.receiptType" />
        </template>
      </el-table-column>
      <el-table-column label="开票状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.CRM_RECEIPT_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['crm:receipt:update']"
          >
            编辑
          </el-button>
          <el-button
            v-if="scope.row.auditStatus === 0"
            v-hasPermi="['crm:receipt:update']"
            link
            type="primary"
            @click="handleSubmit(scope.row)"
          >
            提交审核
          </el-button>
          <el-button
            v-else
            link
            v-hasPermi="['crm:receipt:update']"
            type="primary"
            @click="handleProcessDetail(scope.row)"
          >
            查看审批
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['crm:receipt:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column> -->
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            v-hasPermi="['crm:receipt:query']"
            link
            type="primary"
            @click="openForm('detail', scope.row.id)"
          >
            查看
          </el-button>
          <el-button
            v-if="scope.row.auditStatus === 0"
            v-hasPermi="['crm:receipt:update']"
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
          >
            编辑
          </el-button>
          <el-button
            v-if="scope.row.auditStatus === 0"
            v-hasPermi="['crm:receipt:update']"
            link
            type="primary"
            @click="handleSubmit(scope.row)"
          >
            提交审批
          </el-button>
          <el-button
            v-else
            link
            v-hasPermi="['crm:receipt:update']"
            type="primary"
            @click="handleProcessDetail(scope.row)"
          >
            查看审批
          </el-button>
          <el-button
            v-hasPermi="['crm:receipt:delete']"
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <ReceiptForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import { isEmpty } from '@/utils/is'
import { dateFormatter2 } from '@/utils/formatTime'
import download from '@/utils/download'
import { ReceiptApi, Receipt } from '@/api/crm/receipt'
import ReceiptForm from './ReceiptForm.vue'
import { TabsPaneContext } from 'element-plus'
import * as CustomerApi from '@/api/crm/customer'

/** crm发票管理 列表 */
defineOptions({ name: 'Receipt' })
const { push } = useRouter()

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<Receipt[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  code: undefined,
  customerId: undefined,
  customerName: undefined,
  contractId: undefined,
  contractCode: undefined,
  receiptAmount: undefined,
  receiptDate: [],
  receiptType: undefined,
  titleId: undefined,
  status: undefined,
  processInstanceId: undefined,
  auditStatus: undefined,
  remark: undefined,
  createTime: [],
  ownerUserId: undefined,
  sceneType: '1' // 默认和 activeName 相等
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const customerList = ref<CustomerApi.CustomerVO[]>([]) // 客户列表

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ReceiptApi.getReceiptPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ReceiptApi.deleteReceipt(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除crm发票管理 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await ReceiptApi.deleteReceiptList(checkedIds.value)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: Receipt[]) => {
  checkedIds.value = records.map((item) => item.id)
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ReceiptApi.exportReceipt(queryParams)
    download.excel(data, 'crm发票管理.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const handleTabClick = (tab: TabsPaneContext) => {
  queryParams.sceneType = tab.paneName
  handleQuery()
}

/** 提交审核 **/
const handleSubmit = async (row: Receipt) => {
  await message.confirm(`您确定提交【${row.content}】审核吗？`)
  await ReceiptApi.submitReceipt(row.id)
  message.success('提交审核成功！')
  await getList()
}

/** 查看审批 */
const handleProcessDetail = (row: Receipt) => {
  push({ name: 'BpmProcessInstanceDetail', query: { id: row.processInstanceId } })
}

/** 初始化 **/
onMounted(async () => {
  await getList()
  customerList.value = await CustomerApi.getCustomerSimpleList()
})
</script>
